package com.du.web.sample.controller;

import com.du.web.sample.model.ResBean;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import com.du.web.sample.util.RSAUtil;

@RestController
@RequestMapping("/rsa")
public class RSAController {

    /**
     * 生成RSA密钥对
     */
    @GetMapping("/generate")
    public ResBean<Map<String, String>> generateKeyPair() {
        try {
            Map<String, String> map = RSAUtil.generateKeyPair();
            return ResBean.ok(map);
        } catch (Exception e) {
            return ResBean.error("密钥生成失败: " + e.getMessage());
        }
    }

    /**
     * 公钥加密
     */
    @PostMapping("/encrypt")
    public ResBean<String> encrypt(@RequestParam String publicKey, @RequestParam String plaintext) {
        try {
            String encrypted = RSAUtil.encrypt(publicKey, plaintext);
            return ResBean.ok(encrypted);
        } catch (Exception e) {
            return ResBean.error("加密失败: " + e.getMessage());
        }
    }

    /**
     * 私钥解密
     */
    @PostMapping("/decrypt")
    public ResBean<String> decrypt(@RequestParam String privateKey, @RequestParam String ciphertext) {
        try {
            String decrypted = RSAUtil.decrypt(privateKey, ciphertext);
            return ResBean.ok(decrypted);
        } catch (Exception e) {
            return ResBean.error("解密失败: " + e.getMessage());
        }
    }
} 